﻿#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from datetime import datetime, timedelta, timezone
#获取当前日期和时间
print(datetime.now())
#指定某个日期和时间
dt = datetime(2015, 4, 19, 12)
print(dt)
#datetime转换为timestamp
tt = dt.timestamp()
print(tt)
#timestamp转换为datetime
print(datetime.fromtimestamp(1429427200.0))
print(datetime.utcfromtimestamp(1429427200.0))
#str转换为datetime
cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
print(cday)
#datetime转换为st
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M'))
#datetime加减
now = datetime.now()
print(now)
print(now + timedelta(days=2, hours=12))
#本地时间转换为UTC时间
tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00
print(now.replace(tzinfo=tz_utc_8))
#时区转换
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_dt)
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print(bj_dt)
tokyo_dt = bj_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt)

from collections import namedtuple,deque,defaultdict,OrderedDict
#namedtuple可以很方便地定义一种数据类型，它具备tuple的不变性，又可以根据属性来引用
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
print(isinstance(p, tuple))

#deque是为了高效实现插入和删除操作的双向列表，适合用于队列和栈
q = deque(['a', 'b', 'c'])
q.appendleft('y')
print(q)
dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print(dd['key1'])
print(dd['key2'])

#OrderedDict的Key会按照插入的顺序排列
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od)
print(list(od.keys()))

#Python内置的base64可以直接进行base64的编解码
import base64
print(base64.b64encode(b'binary\x00string'))
print(base64.b64decode(b'YmluYXJ5AHN0cmluZw=='))

#Python的hashlib提供了常见的摘要算法，如MD5，SHA1
import hashlib
md5 = hashlib.md5()
md5 = hashlib.md5()
md5.update('how to use md5 in '.encode('utf-8'))
md5.update('python hashlib?'.encode('utf-8'))
print(md5.hexdigest())
sha1 = hashlib.sha1()
sha1.update('how to use sha1 in '.encode('utf-8'))
sha1.update('python hashlib?'.encode('utf-8'))
print(sha1.hexdigest())

#Python的内建模块itertools提供了非常有用的用于操作迭代对象的函数。
#因为count()会创建一个无限的迭代器，所以上述代码会打印出自然数序列
#cycle()会把传入的一个序列无限重复下去
#repeat()负责把一个元素无限重复下去，不过如果提供第二个参数就可以限定重复次数
import itertools
natuals = itertools.count(2)
for n in natuals:
    print(n)
    if n == 5 :
        break

#无限序列虽然可以无限迭代下去，但是通常我们会通过takewhile()等函数根据条件判断来截取出一个有限的序列
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
print(list(ns))












